/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package imageProcessing.classes;

import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;

/**
 *
 * @author damfercer
 */
public class ImageHelper {
    public static BufferedImage getType4ByteABGRBufferedImage(BufferedImage image){
        BufferedImage res=image;
        if(image.getType()!=BufferedImage.TYPE_4BYTE_ABGR){
            res=ImageHelper.getTransparencyBufferedImage(image);
        }
        return res;
    }
    
    private static BufferedImage getTransparencyBufferedImage(BufferedImage notransparent){
        BufferedImage resultado=new BufferedImage(notransparent.getWidth(), notransparent.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
        Graphics2D createGraphics = resultado.createGraphics();
        createGraphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OUT, 1.0f));
        createGraphics.drawImage(notransparent, 0, 0, null);
        return resultado;
    }
    
    public static BufferedImage deepCopy(BufferedImage bi) {
        ColorModel cm = bi.getColorModel();
        boolean isAlphaPremultiplied = cm.isAlphaPremultiplied();
        WritableRaster raster = bi.copyData(null);
        return new BufferedImage(cm, raster, isAlphaPremultiplied, null);
    }
    
    public static BufferedImage transparencyBlackGrayScale(BufferedImage im){
        BufferedImage grayImage = new BufferedImage(im.getWidth(), im.getHeight(), BufferedImage.TYPE_INT_ARGB);
        for(int x = 0; x < im.getWidth(); x++)
          for(int y = 0; y < im.getHeight(); y++){
               int argb = im.getRGB(x,y);
               
               int a = (argb >> 24) & 0xff;
               int r = (argb >> 16) & 0xff;
               int g = (argb >>  8) & 0xff;
               int b = (argb      ) & 0xff;
               
               int l= (int) (.299 * r + .587 * g + .114 * b); //luminance
               
               grayImage.setRGB(x,y, (a << 24) + (l << 16) + (l << 8) + l);
        }
        return grayImage;
    }
}
